package com.xoa.service.hr.impl;

import com.xoa.dao.common.HrCodeMapper;
import com.xoa.dao.department.DepartmentMapper;
import com.xoa.dao.hr.HrStaffTitleEvaluationMapper;
import com.xoa.dao.users.UsersMapper;
import com.xoa.model.common.HrCode;
import com.xoa.model.common.HrCodeExample;
import com.xoa.model.department.Department;
import com.xoa.model.hr.HrStaffIncentive;
import com.xoa.model.hr.HrStaffIncentiveWithBLOBs;
import com.xoa.model.hr.HrStaffTitleEvaluation;
import com.xoa.model.users.Users;
import com.xoa.service.hr.HrStaffTitleEvaluationService;
import com.xoa.util.CookiesUtil;
import com.xoa.util.DateFormat;
import com.xoa.util.ExcelUtil;
import com.xoa.util.ToJson;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.log.FileUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.page.PageParams;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.zip.DataFormatException;

/**
 * 创建作者:   qizhognxiao
 * 创建日期:   2018-7-20 下午 15:34:32
 * 类介绍  :    工作日志
 * 构造参数:
 */
@Service
public class HrStaffTitleEvaluationServiceImpl implements HrStaffTitleEvaluationService {
    @Autowired
    private HrStaffTitleEvaluationMapper hrStaTitlEvaMapper;
    @Autowired
    private UsersMapper usersMapper;
    @Autowired
    private DepartmentMapper departmentMapper;
    @Autowired
    private HrCodeMapper hrCodeMapper;


    private static final String HR_ITEM="HR_STAFF_TITLE_EVALUATION";

    /**
     * 分页查询所有入职评定人信息
     * @param page
     * @param pageSize
     * @param useFlag
     * @return
     */
    @Override
    public ToJson<HrStaffTitleEvaluation> selectAll(Integer page, Integer pageSize, Boolean useFlag,String byEvaluStaffs) {
        ToJson toJson = new ToJson();
        //分页
        PageParams pageParams = new PageParams();
        pageParams.setPage(page);
        pageParams.setPageSize(pageSize);
        pageParams.setUseFlag(useFlag);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("page", pageParams);
        map.put("byEvaluStaffs",byEvaluStaffs);
        String userName;
        List<HrStaffTitleEvaluation> hrStaTitlEvaList = hrStaTitlEvaMapper.selectAll(map);
        //根据ID将查询评定对象和批准热播的姓名
        for(HrStaffTitleEvaluation hrStaffTitleEvaluation :hrStaTitlEvaList ){
            if(hrStaffTitleEvaluation.getApprovePerson()!=null){
                String userID = hrStaffTitleEvaluation.getApprovePerson();
                userName = usersMapper.getUsernameByUserId(userID);
                hrStaffTitleEvaluation.setUserName(userName);
            }if(hrStaffTitleEvaluation.getByEvaluStaffs() != null){
                String userId = hrStaffTitleEvaluation.getByEvaluStaffs();
                userName = usersMapper.getUsernameByUserId(userId);
                hrStaffTitleEvaluation.setByEvaluStaffsName(userName);
            }
        }
        if(hrStaTitlEvaList.size() > 0){
            toJson.setObj(hrStaTitlEvaList);
            toJson.setMsg("ok");
            toJson.setFlag(0);
        }else{
            toJson.setMsg("err");
            toJson.setFlag(1);
        }
        return toJson;
    }

    /**
     * 创建作者:   qizhognxiao
     * 创建日期:   2018-7-20 下午 15:55:32
     * 方法介绍  :  查询单条入职评定的详细信息。
     */
    @Override
    public ToJson<HrStaffTitleEvaluation> selectByPrimaryKey(Integer evaluationId) {
        ToJson toJson = new ToJson();
        HrStaffTitleEvaluation hrStaffTitleEvaluation = hrStaTitlEvaMapper.selectByPrimaryKey(evaluationId);
        String userName;
        if(hrStaffTitleEvaluation.getApprovePerson()!=null){
            String userID = hrStaffTitleEvaluation.getApprovePerson();
            userName = usersMapper.getUsernameByUserId(userID);
            hrStaffTitleEvaluation.setUserName(userName);
        }
        if(hrStaffTitleEvaluation.getByEvaluStaffs() != null){
            String userId = hrStaffTitleEvaluation.getByEvaluStaffs();
            userName = usersMapper.getUsernameByUserId(userId);
            hrStaffTitleEvaluation.setByEvaluStaffsName(userName);
        }
        if(hrStaffTitleEvaluation != null){
            toJson.setObject(hrStaffTitleEvaluation);
            toJson.setMsg("ok");
            toJson.setFlag(0);
        }else{
            toJson.setMsg("err");
            toJson.setFlag(1);
        }
        return toJson;
    }
    /**
     *
     * 创建作者:   戚中校
     * 创建日期:   2018-7-20 下午16:23:14
     * 方法介绍:   修改某条职位评定记录
     * @return
     */
    @Override
    public ToJson<HrStaffTitleEvaluation> updateByPrimaryKeySelective(HttpServletRequest request,HrStaffTitleEvaluation record) {
        ToJson toJson = new ToJson();
        Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionId);
        record.setCreateUserId(users.getUserId());
        record.setCreateDeptId(users.getDeptId());
        record.setAddTime(new Date());
        if(record.getLastUpdateTime() == null){
            record.setLastUpdateTime(new Date());
        }
        //去掉添加的名字中的逗号
        if (record.getByEvaluStaffs() != null || "".equals(record.getByEvaluStaffs())){
            record.setByEvaluStaffs(record.getByEvaluStaffs().replaceAll(",",""));
        }
        if (record.getApprovePerson() != null || "".equals(record.getApprovePerson())){
            record.setApprovePerson(record.getApprovePerson().replaceAll(",",""));
        }
        int temp = hrStaTitlEvaMapper.updateByPrimaryKey(record);
        if(temp > 0){
            toJson.setMsg("ok");
            toJson.setFlag(0);
        }else{
            toJson.setMsg("err");
            toJson.setFlag(1);
        }
        return toJson;
    }

    /**
     * 删除职位评定记录的方法
     * @param evaluationIds
     * @return
     */
    @Override
    public ToJson<HrStaffTitleEvaluation> deleteAnyEvaByPrimaryKeys(Integer[] evaluationIds) {
        ToJson toJson = new ToJson();
        int temp = hrStaTitlEvaMapper.deleteAnyEvaByPrimaryKeys(evaluationIds);
        if (temp > 0){
            toJson.setMsg("ok");
            toJson.setFlag(0);
        }else{
            toJson.setMsg("err");
            toJson.setFlag(1);
        }
        return toJson;
    }

    /**
     * 添加职称评定信息的方法
     * @param record
     * @return
     */
    @Override
    public ToJson<HrStaffTitleEvaluation> insertSelective(HttpServletRequest request,HrStaffTitleEvaluation record){
        ToJson toJson = new ToJson();
        Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionId);

        record.setCreateUserId(users.getUserId());
        record.setCreateDeptId(users.getDeptId());
        record.setAddTime(new Date());
        record.setLastUpdateTime(new Date());
        if (record.getByEvaluStaffs() != null || "".equals(record.getByEvaluStaffs())){
            record.setByEvaluStaffs(record.getByEvaluStaffs().replaceAll(",",""));
        }
        if (record.getApprovePerson() != null || "".equals(record.getApprovePerson())){
            record.setApprovePerson(record.getApprovePerson().replaceAll(",",""));
        }
        int temp = hrStaTitlEvaMapper.insert(record);
        if(temp > 0){
            toJson.setMsg("添加成功！");
            toJson.setFlag(0);
        }else{
            toJson.setMsg("添加失败！");
            toJson.setFlag(1);
        }
        return toJson;
    }

    /**
     * 创建者：戚中校
     * 方法概述：通过不同的条件查找相关的职位评定信息,并根据传入的值导出列表
     * @param record
     * @return
     */
    @Override
    public ToJson<HrStaffTitleEvaluation> selectByCon(HttpServletRequest request, HttpServletResponse response,HrStaffTitleEvaluation record,Integer page,Integer pageSize,Boolean useFlag,String export,Integer[] deptId) {
        ToJson toJson = new ToJson();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        try {
            if(export==null){
                export="0";
            }
            //分页
            PageParams pageParams = new PageParams();
            pageParams.setPage(page);
            pageParams.setPageSize(pageSize);
            pageParams.setUseFlag(useFlag);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("page", pageParams);
            map.put("deptId", deptId);

            if (record.getStartReportTime() == null || "".equals(record.getStartReportTime())){
                record.setStartReportTime("0000-00-00");
            }
            if (record.getEndReportTime() == null || "".equals(record.getEndReportTime())){
                record.setEndReportTime(df.format(new Date()));
            }
            if (record.getStartReceiveTime() == null || "".equals(record.getStartReceiveTime())){
                record.setStartReceiveTime("0000-00-00");
            }
            if (record.getEndReceiveTime() == null || "".equals(record.getEndReceiveTime())){
                record.setEndReceiveTime(df.format(new Date()));
            }

            /*if(record.getCreateDeptId()!=null && record.getCreateDeptId() != 0){
                if(!StringUtils.checkNull(record.getCreateDeptId().toString())){
                    String fromIds = record.getCreateDeptId().toString();
                    String[] substring = fromIds.split(",");

                }
            }*/


            //去掉传入名字中的逗号
            if (record.getByEvaluStaffs() != null || "".equals(record.getByEvaluStaffs())){
                record.setByEvaluStaffs(record.getByEvaluStaffs().replaceAll(",",""));
            }
            if (record.getApprovePerson() != null || "".equals(record.getApprovePerson())){
                record.setApprovePerson(record.getApprovePerson().replaceAll(",",""));
            }
            map.put("record",record);
            List<HrStaffTitleEvaluation> hrStaTitlEvaList = hrStaTitlEvaMapper.selectByCon(map);
            String userName;
            for(HrStaffTitleEvaluation hrStaffTitleEvaluation : hrStaTitlEvaList){
                if(hrStaffTitleEvaluation.getApprovePerson()!=null){
                    String userID = hrStaffTitleEvaluation.getApprovePerson();
                    userName = usersMapper.getUsernameByUserId(userID);
                    hrStaffTitleEvaluation.setUserName(userName);
                }if(hrStaffTitleEvaluation.getByEvaluStaffs() != null){
                    String userId = hrStaffTitleEvaluation.getByEvaluStaffs();
                    userName = usersMapper.getUsernameByUserId(userId);
                    hrStaffTitleEvaluation.setByEvaluStaffsName(userName);
                }

            }
            toJson.setObj(hrStaTitlEvaList);
            toJson.setMsg("ok");
            toJson.setFlag(0);
            //当export为1时   执行导出功能
            if(export.equals("1")) {
                HSSFWorkbook workbooks = new HSSFWorkbook();
                //HSSFCellStyle styleTitle = createStyle(workbook, (short)16);
                HSSFCellStyle style = workbooks.createCellStyle();
                style.setAlignment(HorizontalAlignment.CENTER);
                style.setVerticalAlignment(VerticalAlignment.CENTER);
                // 创建一个字体样式
                HSSFFont font = workbooks.createFont();
                font.setFontHeightInPoints((short)16);
                font.setBold(true);
                style.setFont(font);
                HSSFSheet sheet = workbooks.createSheet("职位评定信息导出");
                sheet.setDefaultColumnWidth(25);
                sheet.setDefaultRowHeightInPoints(25);
                CellRangeAddress cellRangeAddress = new CellRangeAddress(0, 0, 0, 13);
                sheet.addMergedRegion(cellRangeAddress);
                HSSFRow rowTitle = sheet.createRow(0);
                HSSFCell cellTitle = rowTitle.createCell(0);
                // 为标题设置背景颜色
                style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
                style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.index);
                cellTitle.setCellValue("职位评定信息导出");
                cellTitle.setCellStyle(style);
                String[] secondTitles = {"评定对象", "评定对象用户名", "批准人", "获取职称", "获取方式", "申报时间", "获取时间", "下次申报职称","下次申报时间","聘用职务","聘用单位","聘用开始时间","聘用结束时间","评定详情"};
                HSSFWorkbook workbook2 = ExcelUtil.makeSecondHead(workbooks, secondTitles);
                int i = 1;
                for (HrStaffTitleEvaluation hrStaffTitleEvaluation :hrStaTitlEvaList) {
                    //转换日期格式
                    if(hrStaffTitleEvaluation.getReportTime() != null){
                        hrStaffTitleEvaluation.setReportTime1(DateFormat.getDatestr(hrStaffTitleEvaluation.getReportTime()));
                    }
                    if(hrStaffTitleEvaluation.getReceiveTime() != null){
                        hrStaffTitleEvaluation.setReceiveTime1(DateFormat.getDatestr(hrStaffTitleEvaluation.getReceiveTime()));
                    }
                    if(hrStaffTitleEvaluation.getApproveNextTime() != null){
                        hrStaffTitleEvaluation.setApproveNextTime1(DateFormat.getDatestr(hrStaffTitleEvaluation.getApproveNextTime()));
                    }
                    if(hrStaffTitleEvaluation.getStartDate() != null){
                        hrStaffTitleEvaluation.setStartDate1(DateFormat.getDatestr(hrStaffTitleEvaluation.getStartDate()));
                    }
                    if(hrStaffTitleEvaluation.getEndDate() != null){
                        hrStaffTitleEvaluation.setEndDate1(DateFormat.getDatestr(hrStaffTitleEvaluation.getEndDate()));
                    }

                    if(hrStaffTitleEvaluation.getApprovePerson()!=null){
                        String userID = hrStaffTitleEvaluation.getApprovePerson();
                        userName = usersMapper.getUsernameByUserId(userID);
                        hrStaffTitleEvaluation.setUserName(userName);
                    }if(hrStaffTitleEvaluation.getByEvaluStaffs() != null){
                        String userId = hrStaffTitleEvaluation.getByEvaluStaffs();
                        userName = usersMapper.getUsernameByUserId(userId);
                        Users usersByuserId = usersMapper.getUsersByuserId(userId);
                        hrStaffTitleEvaluation.setByEvaluStaffs(usersByuserId.getByname());
                        hrStaffTitleEvaluation.setByEvaluStaffsName(userName);
                    }
                    if(hrStaffTitleEvaluation.getGetMethod() != null){
                        if(hrStaffTitleEvaluation.getGetMethod().equals("1")){
                           hrStaffTitleEvaluation.setGetMethodName("业绩考核");
                        }else if(hrStaffTitleEvaluation.getGetMethod().equals("2")){
                           hrStaffTitleEvaluation.setGetMethodName("考试");
                        }
                    }

                    hrStaffTitleEvaluation.setId(i);
                    i++;
                }
                String[] beanProperty = {"byEvaluStaffsName", "byEvaluStaffs", "userName", "postName", "getMethodName", "reportTime1", "receiveTime1","approveNext","approveNextTime1","employPost","employCompany","startDate1","endDate1","remark"};
                HSSFWorkbook workbook = ExcelUtil.exportExcelData(workbook2, hrStaTitlEvaList, beanProperty);
                ServletOutputStream out = response.getOutputStream();
                String filename = "职位评定信息导出.xls"; //考虑多语言
                filename = FileUtils.encodeDownloadFilename(filename,
                        request.getHeader("user-agent"));
                response.setContentType("application/vnd.ms-excel");
                response.setHeader("content-disposition",
                        "attachment;filename=" + filename);
                workbook.write(out);
                out.close();
            }

        } catch (Exception e) {
            toJson.setMsg(e.getMessage());
            toJson.setFlag(1);
        }

        return toJson;
    }

    /**
     * 导入功能
     * @param request
     * @param response
     * @param file
     * @return
     */
    @Override
    public ToJson<HrStaffTitleEvaluation> importIncentiveInfo(HttpServletRequest request, HttpServletResponse response, MultipartFile file) {
        ToJson<HrStaffTitleEvaluation> json = new ToJson<HrStaffTitleEvaluation>(1,"error");
        InputStream in=null;
        try {
            //判读当前系统
            //读取配置文件
            ResourceBundle rb = ResourceBundle.getBundle("upload");
            String osName = System.getProperty("os.name");
            StringBuffer path = new StringBuffer();
                 StringBuffer buffer=new StringBuffer();
        if(osName.toLowerCase().startsWith("win")){
            //sb=sb.append(rb.getString("upload.win"));
            //判断路径是否是相对路径，如果是的话，加上运行的路径
            String uploadPath = rb.getString("upload.win");
            if(uploadPath.indexOf(":")==-1){
                //获取运行时的路径
                String basePath = this.getClass().getClassLoader().getResource(".").getPath()+ File.pathSeparator;
                //获取截取后的路径
                String str2 = "";
                if(basePath.indexOf("/xoa")!=-1){
                    //获取字符串的长度
                    int length = basePath.length();
                    //返回指定字符在此字符串中第一次出现处的索引
                    int index = basePath.indexOf("/xoa");
                    //从指定位置开始到指定位置结束截取字符串
                    str2=basePath.substring(0,index);
                }
                path = path.append(str2 + "/xoa");
            }
            path.append(uploadPath);
            buffer=buffer.append(rb.getString("upload.win"));
        }else{
            path=path.append(rb.getString("upload.linux"));
            buffer=buffer.append(rb.getString("upload.linux"));
        }
            int success=0;
            // 判断是否为空文件
            if (file.isEmpty()) {
                json.setMsg("请上传文件！");
                json.setFlag(1);
                return json;
            } else {
                String fileName = file.getOriginalFilename();
                if (fileName.endsWith(".xls") || fileName.endsWith(".xlsx")) {
                    String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                    int pos = fileName.indexOf(".");
                    String extName = fileName.substring(pos);
                    String newFileName = uuid + extName;
                    File dest = new File(path.toString(), newFileName);
                    file.transferTo(dest);
                    // 将文件上传成功后进行读取文件
                    // 进行读取的路径
                    String readPath = path.append(System.getProperty("file.separator")).append(newFileName).toString();
                    in = new FileInputStream(readPath);
                   HSSFWorkbook excelObj = new HSSFWorkbook(in);
                   HSSFSheet sheetObj = excelObj.getSheetAt(0);
                    Row row = sheetObj.getRow(1);
                    int colNum = row.getPhysicalNumberOfCells();
                    int lastRowNum = sheetObj.getLastRowNum();
                    HrStaffTitleEvaluation hrStaffTitleEvaluation = null;
                    for (int i = 2; i < lastRowNum-1; i++) {
                        hrStaffTitleEvaluation = new HrStaffTitleEvaluation();
                        row = sheetObj.getRow(i);
                        String value = "";
                        if (row != null) {
                            for (int j = 0; j < colNum; j++) {
                                Cell cell = row.getCell(j);
                                if (cell != null) {
                                    switch (j) {
                                        case 0:
                                            // 评定对象
                                            if (cell.getStringCellValue() != null) {
                                                hrStaffTitleEvaluation.setByEvaluStaffsName(cell.getStringCellValue());
                                            }
                                            break;
                                        case 1:
                                            // 评定对象用户名
                                            hrStaffTitleEvaluation.setByEvaluStaffs(cell.getStringCellValue());
                                            break;
                                        case 2:
                                            //批准人
                                                Users user = usersMapper.getUserByUserName(cell.getStringCellValue());

                                                    hrStaffTitleEvaluation.setApprovePerson(user.getUserId());



                                            break;
                                        case 3:
                                            // 获取职称
                                            if (cell.getStringCellValue() != null) {
                                                hrStaffTitleEvaluation.setPostName(cell.getStringCellValue());
                                            }
                                            break;
                                        case 4:
                                            // 获取方式
                                            if (cell.getStringCellValue() != null) {
                                                if(cell.getStringCellValue().equals("业绩考核")){
                                                    hrStaffTitleEvaluation.setGetMethod("1");
                                                }else if(cell.getStringCellValue().equals("考试")){
                                                    hrStaffTitleEvaluation.setGetMethod("2");
                                                }
                                            }
                                            break;
                                        case 5:
                                            // 申报时间
                                            if (cell.getCellType() == CellType.NUMERIC) {
                                                short format = cell.getCellStyle().getDataFormat();
                                                SimpleDateFormat sdf = null;
                                                if (format == 14 || format == 31 || format == 57 || format == 58) {
                                                    //日期
                                                    sdf = new SimpleDateFormat("yyyy-MM-dd");
                                                }
                                                double v = cell.getNumericCellValue();
                                                Date date = org.apache.poi.ss.usermodel.DateUtil.getJavaDate(v);
                                                hrStaffTitleEvaluation.setReportTime(date);
                                                break;
                                            }
                                            hrStaffTitleEvaluation.setReportTime(DateFormat.DateToStr(cell.getStringCellValue()));
                                            break;
                                        case 6:
                                            //获取时间
                                            if (cell.getCellType() == CellType.NUMERIC) {
                                                short format = cell.getCellStyle().getDataFormat();
                                                SimpleDateFormat sdf = null;
                                                if (format == 14 || format == 31 || format == 57 || format == 58) {
                                                    //日期
                                                    sdf = new SimpleDateFormat("yyyy-MM-dd");
                                                }
                                                double v = cell.getNumericCellValue();
                                                Date date = org.apache.poi.ss.usermodel.DateUtil.getJavaDate(v);
//                                                result = sdf.format(date);
                                                hrStaffTitleEvaluation.setReceiveTime(date);
                                                break;
                                            }
                                            hrStaffTitleEvaluation.setReceiveTime(DateFormat.DateToStr(cell.getStringCellValue()));
                                            break;
                                        case 7:
                                            // 下次申报职称
                                            hrStaffTitleEvaluation.setApproveNext(cell.getStringCellValue());
                                            break;
                                        case 8:
                                            // 下次申报时间
                                            if (cell.getCellType() == CellType.NUMERIC) {
                                                short format = cell.getCellStyle().getDataFormat();
                                                SimpleDateFormat sdf = null;
                                                if (format == 14 || format == 31 || format == 57 || format == 58) {
                                                    //日期
                                                    sdf = new SimpleDateFormat("yyyy-MM-dd");
                                                }
                                                double v = cell.getNumericCellValue();
                                                Date date = org.apache.poi.ss.usermodel.DateUtil.getJavaDate(v);
//                                                result = sdf.format(date);
                                                hrStaffTitleEvaluation.setApproveNextTime(date);
                                                break;
                                            }
                                            hrStaffTitleEvaluation.setApproveNextTime(DateFormat.DateToStr(cell.getStringCellValue()));
                                            break;
                                        case 9:
                                            //聘用职务
                                            hrStaffTitleEvaluation.setEmployPost(cell.getStringCellValue());
                                            break;
                                        case 10:
                                            //聘用单位
                                            hrStaffTitleEvaluation.setEmployCompany(cell.getStringCellValue());
                                            break;
                                        case 11:
                                            //聘用开始时间
                                            if (cell.getCellType() == CellType.NUMERIC) {
                                                short format = cell.getCellStyle().getDataFormat();
                                                SimpleDateFormat sdf = null;
                                                if (format == 14 || format == 31 || format == 57 || format == 58) {
                                                    //日期
                                                    sdf = new SimpleDateFormat("yyyy-MM-dd");
                                                }
                                                double v = cell.getNumericCellValue();
                                                Date date = org.apache.poi.ss.usermodel.DateUtil.getJavaDate(v);
//                                                result = sdf.format(date);
                                                hrStaffTitleEvaluation.setStartDate(date);
                                                break;
                                            }
                                            hrStaffTitleEvaluation.setStartDate(DateFormat.DateToStr(cell.getStringCellValue()));
                                            break;
                                        case 12:
                                            //聘用结束时间
                                            if (cell.getCellType() == CellType.NUMERIC) {
                                                short format = cell.getCellStyle().getDataFormat();
                                                SimpleDateFormat sdf = null;
                                                if (format == 14 || format == 31 || format == 57 || format == 58) {
                                                    //日期
                                                    sdf = new SimpleDateFormat("yyyy-MM-dd");
                                                }
                                                double v = cell.getNumericCellValue();
                                                Date date = org.apache.poi.ss.usermodel.DateUtil.getJavaDate(v);
//                                                result = sdf.format(date);
                                                hrStaffTitleEvaluation.setEndDate(date);
                                                break;
                                            }
                                            hrStaffTitleEvaluation.setEndDate(DateFormat.DateToStr(cell.getStringCellValue()));
                                            break;
                                        case 13:
                                            hrStaffTitleEvaluation.setRemark(cell.getStringCellValue());
                                            break;

                                    }

                                }
                            }
                            if(hrStaffTitleEvaluation!=null){
                                Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
                                Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionId);

                                hrStaffTitleEvaluation.setCreateUserId(user.getUserId());
                                hrStaffTitleEvaluation.setCreateDeptId(user.getDeptId());
                                hrStaffTitleEvaluation.setAddTime(new Date());
                                hrStaffTitleEvaluation.setLastUpdateTime(new Date());

                                int a = hrStaTitlEvaMapper.insertSelective(hrStaffTitleEvaluation);
                                if (a!=0){
                                    success = success + 1;
                                }
                            }

                        }
                    }
                }

            }
            HrStaffTitleEvaluation temp=new HrStaffTitleEvaluation();
            temp.setCount(success);
            json.setFlag(0);
            json.setMsg("ok");
            json.setObject(temp);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg("数据保存异常");
            json.setFlag(1);
        } finally {
            try {
                if(in!=null){
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return json;
    }


    /**
     * 获取奖惩下拉框的内容（人事代码表）
     * @param type
     * @return
     */
    @Override
    public ToJson<HrCode> getHrCodes(String type) {
        ToJson<HrCode> toJson = new ToJson<>();
        List<HrCode> hrCodes = new ArrayList<>();
        HrCodeExample hrCodeExample = new HrCodeExample();
        HrCodeExample.Criteria criteria = hrCodeExample.createCriteria();
        hrCodeExample.setOrderByClause("cast(CODE_NO as SIGNED INTEGER) ASC");
        if ("item".equals(type)) {
            criteria.andParentNoEqualTo(HR_ITEM);
            hrCodes = hrCodeMapper.selectByExampleWithBLOBs(hrCodeExample);
        }
        toJson.setMsg("ok");
        toJson.setFlag(0);
        toJson.setObject(hrCodes);
        return toJson;
    }

    /**
     * 根据条件查询数量
     * @param
     * @param deptId(传入的多个部门的编号)
     * @return 返回的json字符串中  nums是返回的结果的数量
     *
     */
    @Override
    public ToJson<HrStaffTitleEvaluation> selectNumByCon(HrStaffTitleEvaluation record, Integer[] deptId) {
        ToJson toJson = new ToJson();
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            if (deptId != null && deptId.length > 0){
                map.put("deptId",deptId);
            }
            map.put("record",record);
            List<HrStaffTitleEvaluation> list = hrStaTitlEvaMapper.selectNumByCon(map);

            for(HrStaffTitleEvaluation hrStaffTitleEvaluation:list){
                if (hrStaffTitleEvaluation.getGetMethod() != null) {
                    if (hrStaffTitleEvaluation.getGetMethod().equals("1")) {
                        hrStaffTitleEvaluation.setGetMethodName("业绩考核");
                    } else if (hrStaffTitleEvaluation.getGetMethod().equals("2")) {
                        hrStaffTitleEvaluation.setGetMethodName("考试");
                    } else {
                        hrStaffTitleEvaluation.setGetMethodName("其它");
                    }
                }
            }
            if(list.size() >= 0){
                toJson.setObj(list);
                toJson.setMsg("ok");
                toJson.setFlag(0);
            }else{
                toJson.setMsg("err");
                toJson.setFlag(1);
            }

        }catch (Exception e){
            toJson.setMsg("err");
            toJson.setFlag(1);
        }
        return toJson;
    }


    /**
     * 查询当前用户数据
     * @param uId
     * @return
     */
    public List<HrStaffTitleEvaluation> getUserName(String uId){
        String userName;
        List<HrStaffTitleEvaluation> hrStaTitlEvaList = hrStaTitlEvaMapper.getHrStaffContractList(uId);
        for(HrStaffTitleEvaluation hrStaffTitleEvaluation :hrStaTitlEvaList ){
            if(hrStaffTitleEvaluation.getApprovePerson()!=null){
                String userID = hrStaffTitleEvaluation.getApprovePerson();
                userName = usersMapper.getUsernameByUserId(userID);
                hrStaffTitleEvaluation.setUserName(userName);
            }if(hrStaffTitleEvaluation.getByEvaluStaffs() != null){
                String userId = hrStaffTitleEvaluation.getByEvaluStaffs();
                userName = usersMapper.getUsernameByUserId(userId);
                hrStaffTitleEvaluation.setByEvaluStaffsName(userName);
            }
        }
        return hrStaTitlEvaList;
    }

    @Override
    public ToJson<HrStaffTitleEvaluation> getByStaffName(String staffName, Integer page, Integer pageSize, boolean useFlag) {
        ToJson<HrStaffTitleEvaluation> json=new ToJson<HrStaffTitleEvaluation>();
        //分页
        PageParams pageParams = new PageParams();
        pageParams.setPage(page);
        pageParams.setPageSize(pageSize);
        pageParams.setUseFlag(useFlag);
        HashMap<String,Object> map = new HashMap();
        map.put("pageParams", pageParams);
        map.put("staffName",staffName);
        try{
            List<HrStaffTitleEvaluation> list=hrStaTitlEvaMapper.getByStaffName(map);
            if(list.size()>0){
                for(HrStaffTitleEvaluation title:list){
                    if(title.getByEvaluStaffs()!=null){
                        Users user = usersMapper.findUsersByuserId(title.getByEvaluStaffs()); //根据 id 找名字
                        if(user!=null){
                            title.setByEvaluStaffs(user.getUserName());
                        }else{
                            title.setByEvaluStaffs(" ");
                        }
                    }
                    if(title.getApprovePerson()!=null){
                        Users user = usersMapper.findUsersByuserId(title.getApprovePerson()); //根据 id 找名字
                        if(user!=null){
                            title.setApprovePerson(user.getUserName());
                        }
                    }
                    //获取方式
                    HrCode hr_staff_contract2 = hrCodeMapper.selectCode("HR_STAFF_TITLE_EVALUATION",title.getGetMethod());
                    if (hr_staff_contract2 != null) {
                        title.setGetMethod(hr_staff_contract2.getCodeName());
                    } else {
                        title.setGetMethod(" ");
                    }
                }
                json.setObj(list);
            }
            json.setTotleNum(hrStaTitlEvaMapper.getByStaffNameCount(staffName));
            json.setFlag(0);
            json.setMsg("true");
        }catch (Exception e){
            e.printStackTrace();
            json.setMsg("err");
            json.setFlag(1);
        }
        return json;
    }
}
